import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { User } from './user.entity'
import { Repository, DeleteResult } from 'typeorm'
import { CreateUserDto } from './create-user.dto'

@Injectable()
export class UserService {
  constructor(
    //通过该注解加上Entity实例可以得到一个usersRepository实例，该实例可以帮助我们进行数据库的查询
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>
  ) {}
  // 获取数据
  findOne(id: number): Promise<User> {
    return this.usersRepository.findOneBy({ id })
  }
  // 新增数据
  createOneData(payload: CreateUserDto): Promise<User> {
    // 1、创建一个user实例
    const user = new User()
    // 2、进行一一的映射
    user.username = payload.username
    user.password = payload.password
    user.role = payload.role
    user.nickname = payload.nickname
    user.avatar = payload.avatar
    user.active = 1
    // 3、调用save方法新增数据
    return this.usersRepository.save(user)
  }
  // 删除数据
  deleteOneData(id: string): Promise<DeleteResult> {
    this.usersRepository.delete(id)
    throw new HttpException('删除数据成功', HttpStatus.FORBIDDEN)
  }
}
